/* **********************************************************************************
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* This source code is subject to terms and conditions of the Shared Source License
* for DSL Editor PowerToy. A copy of the license can be found in the License.htm file
* at the root of this distribution. If you can not locate the Shared Source License
* for DSL Editor PowerToy, please obtain a copy from: http://www.codeplex.com/dsltreegrideditor/Project/License.aspx.
* By using this source code in any fashion, you are agreeing to be bound by
* the terms of the Shared Source License for DSL Editor PowerToy.
*
* You must not remove this notice, or any other, from this software.
*
* **********************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

using EnvDTE;
using EnvDTE80;

using Microsoft.Practices.RecipeFramework;
using Microsoft.Practices.RecipeFramework.Library;

namespace DslEditorPowerToy.Recipes.Actions
{
    /// <summary>
    /// Appends a line(s) of text to a text file, relative to line(s) containing specificed text
    /// </summary>
    public class AppendLineToTextFileAction : ActionBase
    {
        private EnvDTE.Project _project = null;
        private string _targetFilePath = string.Empty;
        private string _searchExpression = string.Empty;
        private string _appendText = string.Empty;
        private AppendPosition _position = AppendPosition.After;
        private AppendOccurance _occurance = AppendOccurance.Any;

        #region Constructors
        public AppendLineToTextFileAction()
            : base()
        {
        }
        #endregion

        #region Public Properties
        [Input(Required=true)]
        [CLSCompliant(false)]
        public EnvDTE.Project Project
        {
            get
            {
                return this._project;
            }
            set
            {
                this._project = value;
            }
        }
        [Input(Required=true)]
        public string TargetFilePath
        {
            get
            {
                return this._targetFilePath;
            }
            set
            {
                this._targetFilePath = value;
            }
        }
        [Input(Required=true)]
        public string SearchExpression
        {
            get
            {
                return this._searchExpression;
            }
            set
            {
                this._searchExpression = value;
            }
        }
        [Input(Required=true)]
        public string AppendText
        {
            get
            {
                return this._appendText;
            }
            set
            {
                this._appendText = value;
            }
        }
        [Input(Required=false)]
        public AppendPosition Position
        {
            get
            {
                return this._position;
            }
            set
            {
                this._position = value;
            }
        }
        [Input(Required=false)]
        public AppendOccurance Occurance
        {
            get
            {
                return this._occurance;
            }
            set
            {
                this._occurance = value;
            }
        }
        #endregion

        #region IAction Members

        public override void Execute()
        {
            base.Execute();
            ValidateParameters();

            //Get file from project
            string pathToFile = Path.Combine(DteHelper.BuildPath(this._project), (string)this.Evaluate(this._targetFilePath));
            ProjectItem projectItem = DteHelper.FindItemByPath(DTE.Solution, pathToFile);
            if (null == projectItem)
                return;

            try
            {
                //Open document in silent mode
                projectItem.Open(Constants.vsViewKindTextView);

                //Get to start of text document
                TextDocument document = projectItem.Document.Object("TextDocument") as TextDocument;
                EditPoint editPoint = document.CreateEditPoint(null);

                //Find first Match
                EditPoint endPoint = null;
                TextRanges tags = null;
                string searchExpression = Regex.Escape((string)this.Evaluate(Regex.Unescape(this._searchExpression)));
                bool found = editPoint.FindPattern(searchExpression, (int)(FindOptions.RegularExpression | FindOptions.FromStart),
                    ref endPoint, ref tags);
                if (false == found)
                    return;

                while (true == found)
                {
                    if (AppendOccurance.First == this._occurance)
                    {
                        //Only append for first match
                        AppendLine(editPoint, this._appendText, editPoint.Line, this._position);
                        break;
                    }
                    else if (AppendOccurance.Any == this._occurance)
                    {
                        //Append all matched
                        AppendLine(editPoint, this._appendText, editPoint.Line, this._position);
                    }

                    //Find next Match
                    editPoint.MoveToAbsoluteOffset(endPoint.AbsoluteCharOffset);
                    endPoint = null;
                    tags = null;
                    found = editPoint.FindPattern(searchExpression, (int)(FindOptions.RegularExpression),
                    ref endPoint, ref tags);
                }
                if (AppendOccurance.Last == this._occurance)
                {
                    //Append last matched
                    AppendLine(editPoint, this._appendText, editPoint.Line, this._position);
                }


                //Ensure it is closed
                projectItem.Document.Close(vsSaveChanges.vsSaveChangesYes);
            }
            finally
            {
                //Ensure its closed
                if (null != projectItem.Document)
                    projectItem.Document.Close(vsSaveChanges.vsSaveChangesNo);
            }
        }

        public override void Undo()
        {
            //Do undo action, or explain why you can't or should not
        }

        #endregion

        #region Protected Methods
        /// <summary>
        /// Validates parameters before execution
        /// </summary>
        protected override void ValidateParameters()
        {
            if (null == this._project)
                throw new ArgumentNullException("Project");
            if (null == this._targetFilePath)
                throw new ArgumentNullException("TargetFilePath");
            if (0 == this._targetFilePath.Length)
                throw new ArgumentOutOfRangeException("TargetFilePath");
            if (null == this._searchExpression)
                throw new ArgumentNullException("SearchText");
            if (0 == this._searchExpression.Length)
                throw new ArgumentOutOfRangeException("SearchText");
            if (null == this._appendText)
                throw new ArgumentNullException("AppendText");
            if (0 == this._appendText.Length)
                throw new ArgumentOutOfRangeException("AppendText");
        }
        #endregion

        #region Private Methods
        /// <summary>
        /// Appends a line of text to position of given line
        /// </summary>
        /// <param name="p"></param>
        /// <param name="p_2"></param>
        /// <param name="appendPosition"></param>
        private void AppendLine(EditPoint editPoint, string appendText, 
            int line, AppendPosition appendPosition)
        {
            //Move to position
            editPoint.MoveToLineAndOffset(line, 1);
            if (AppendPosition.After == appendPosition)
                editPoint.LineDown(1);

            //Insert a new line
            ((EditPoint2)editPoint).InsertNewLine(1);
            editPoint.LineUp(1);

            //Insert text
            editPoint.Insert((string)this.Evaluate(this._appendText));
        }
        #endregion
    }
}
